package com.dgut.doctorservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dgut.doctorservice.entity.DepartmentInfo;
import com.dgut.doctorservice.entity.excel.DepartmentData;
import com.dgut.doctorservice.service.DepartmentInfoService;
import com.dgut.servicebase.exceptionhandler.DoctorException;

import java.util.Map;


public class DepartmentExcelListener extends AnalysisEventListener<DepartmentData> {

    public DepartmentExcelListener(DepartmentInfoService departmentInfoService) {
        this.departmentInfoService = departmentInfoService;
    }
    public DepartmentExcelListener() {

    }



    public DepartmentInfoService departmentInfoService;



    @Override
    public void invoke(DepartmentData departmentData, AnalysisContext analysisContext) {
        if (departmentData==null){
            throw new DoctorException(20001,"文件数据为空");
        }
        //一次读一行
        DepartmentInfo oneDepartmentInfo = this.existOnceDepartment(departmentInfoService, departmentData.getFirstDepartment());

        if (oneDepartmentInfo==null){
            oneDepartmentInfo=new DepartmentInfo();
            oneDepartmentInfo.setParentId("0");
            oneDepartmentInfo.setName(departmentData.getFirstDepartment());

            departmentInfoService.save(oneDepartmentInfo);
        }

        String pid=oneDepartmentInfo.getId();

        DepartmentInfo secondDepartmentInfo = this.existOnceNextDepartment(departmentInfoService, departmentData.getSecondDepartment(), pid);
        if (secondDepartmentInfo==null){
            secondDepartmentInfo=new DepartmentInfo();
            secondDepartmentInfo.setParentId(pid);
            secondDepartmentInfo.setName(departmentData.getSecondDepartment());
            departmentInfoService.save(secondDepartmentInfo);
        }


    }

    //判断一级二级科室不能重复添加
    private DepartmentInfo existOnceDepartment(DepartmentInfoService departmentInfoService,String name){
        QueryWrapper<DepartmentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        wrapper.eq("parent_id","0");
        DepartmentInfo one = departmentInfoService.getOne(wrapper);
        return one;
    }
    private DepartmentInfo existOnceNextDepartment(DepartmentInfoService departmentInfoService,String name,String pid){
        QueryWrapper<DepartmentInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("name",name);
        wrapper.eq("parent_id",pid);
        DepartmentInfo one = departmentInfoService.getOne(wrapper);
        return one;
    }

    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        super.invokeHeadMap(headMap, context);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
